package com.zbs.framework.chat.customer;

import com.alibaba.fastjson.JSONObject;
import com.zbs.framework.chat.constants.WebSocketConstants;
import com.zbs.framework.chat.entity.RemoteMessage;
import com.zbs.framework.chat.websocket.UserWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;


/**
 * 订阅者-消费处理业务逻辑
 *
 * @author zhengkegui
 * @date 2022/2/25 15:43
 */
@Component
@Slf4j
public class WebSocketRedisSubscriber implements MessageListener {

    @Autowired
    private UserWebSocketServer userWebSocketServer;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());// 订阅的频道名称
        String msg = "";
        try {
            msg = new String(message.getBody(), StandardCharsets.UTF_8);//注意与发布消息编码一致，否则会乱码
            if (!ObjectUtils.isEmpty(msg)) {
                // 最新消息
                if (WebSocketConstants.REDIS_CHANNEL.endsWith(channel)){
                    log.info("redis 队列收到消息:{}",msg);
                    userWebSocketServer.sendMessage(JSONObject.parseObject(msg, RemoteMessage.class));
                }

            } else {
                log.info("消息内容为空，不处理。");
            }
        } catch (Exception e) {
            log.error("处理消息异常：" + e.toString());
            e.printStackTrace();
        }

    }
}